#define __LIBRARY__
#include <stdio.h>
#include <linux/sem.h>
#include <unistd.h>
#include <sys/types.h>
#include <linux/shm.h>


#define bufsize 10
#define number  530

_syscall2(sem_t*,sem_open,const char *,name,unsigned int,value);
_syscall1(int,sem_wait,sem_t*,sem);
_syscall1(int,sem_post,sem_t*,sem);
_syscall1(int,sem_unlink,const char *,name);

_syscall3(int,shmget,key_t,key,size_t,size,int,shmflg);
_syscall3(void*,shmmat,int,shmid,const void*,shmaddr,int,shmflg);
_syscall1(int,shmctl,int,shmid);



int main()
{

    sem_t* empty = NULL;
    sem_t* full = NULL;
    sem_t* mutex = NULL;
    int i = 0;
    int shmid;
    int bufin = 0;
    int* ptr = NULL;

    empty = sem_open("empty", bufsize);
    full = sem_open("full", 0);
    mutex = sem_open("mutex", 1);

    shmid = shmget((key_t)1234, bufsize, 0);

    if (shmid == -1)
    {
        printf("shmid errno\n");
        return 0;
    }
    printf("producer shmid : %d\n", shmid);
    fflush(stdout);

    ptr = (int*)shmmat(shmid, NULL, 0);
   
    for (i = 1;i <= number;i++)
    {
        sem_wait(empty);
        sem_wait(mutex);

        ptr[bufin] = i;
        bufin = (bufin + 1) % 10;

        sem_post(mutex);
        sem_post(full);
    }

    sem_unlink("empty");
    sem_unlink("full");
    sem_unlink("mutex");

    shmctl(shmid);
    printf("producer exit\n");
    return 0;
}